package com.attilax.user;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

 

 



















import javax.persistence.NonUniqueResultException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import aaaCfg.IocX4jobus;

import com.attilax.agt.CantSetSelfEx;
import com.attilax.agt.SuperiorExistEx;
import com.attilax.biz.seo.getConnEx;
import com.attilax.db.DbServiceV3Q68;
import com.attilax.db.DbServiceV4qb9;
import com.attilax.ex.UidEmptyEx;
 
import com.attilax.exception.ExUtil;
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.net.requestImp;
import com.attilax.orm.AtiOrm;
import com.attilax.secury.LoginException;
import com.attilax.sql.SqlService;
import com.attilax.sql.ex.DuplicateEntryEx;
import com.attilax.token.TokenService;
import com.attilax.token.TokenServiceV2;
import com.attilax.token.TokenServiceV4;
import com.attilax.user.ex.OtherUserEx;
import com.attilax.user.ex.UserExistEx;
import com.attilax.user.ex.UserNotExistEx;
import com.csmy.my.center.module.CustomerInfo;
import com.csmy.my.center.module.MemeberInfo;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.google.inject.Inject;

/**
 * com.attilax.user.AgentService
 * @author attilax
 *2016年6月10日 下午5:24:49
 */
public class AgentService extends UserSrv_4game {
	
	public static void main(String[] args) {
	//	UserService us=	IocX4jobus.getBean(UserService.class);
	//	System.out.println(us.getCurUserinfo());
	//	System.out.println();
		System.setProperty("agent_cfgfile", "cfg_game.properties");
		AgentService a=com.attilax.ioc.Ioc4agent.getBean(AgentService.class);
		 
		
	//	a.login(  "888","000");
		String sql="insert agent(uid,pwd)values('$uid$','$pwd$') ";
		sql=sql.replace("$uid$", "888");
		
		sql=sql.replace("$pid$", "");
		sql=sql.replace("$pwd$", "111111");
		System.out.println(sql);
//		try {
//			a.dbsvrV4.executeUpdateV2qb0(sql);
//		} catch (getConnEx | DuplicateEntryEx | SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		try {
			a.login4hiagt("200005", "111111");
		} catch (UserNotExistEx e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//	 try {
//		 Cookie ck=new Cookie("null_uid_agentUtype", "99");
//		requestImp ri=new requestImp();
//		ri.addCookie(ck);
//		Global.req.set(ri);
//		
//		//a.setSubAgent("888888");
//		
//	} catch (CantSetSelfEx | SuperiorExistEx | UserNotExistEx e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (DuplicateEntryEx e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
	//	System.out.println(a.login("admin","admin"));
		System.out.println("---0-0f");
	}
	
	@Inject
	DbServiceV3Q68 dbsvr;
	
	@Inject
	public 	DbServiceV4qb9 dbsvrV4;
	@Inject
	TokenServiceV2 tksvr;
	
	@Inject
	TokenServiceV4 tksvrV4;
	/**
	attilax    2016年6月10日  下午4:49:46
	 * @param string
	 * @param string2
	 */
	public Object login(String uname, String pwd) {
	Map m = getUserinfoByUid(uname);
	if(m==null)
		throw new LoginException("ex:user_not_exist:此用户不存在");
	if(pwd.equals(m.get("pwd").toString()))
	{
		tksvr.setUtype("agent").setToken(uname, uname);
		tksvr.setTokenKeyVal("urole", "agent");
		if(m.get("parent_id")!=null)
			if(m.get("parent_id").equals("0"))
			tksvr.setTokenKeyVal("urole", "admin");
		return m;
	}
	throw new LoginException("ex:pwd_err:密码错误");
	
		
	}
	
	/**
	attilax    2016年6月10日  下午4:49:46
	 * @param string
	 * @param string2
	 * @throws UserNotExistEx 
	 */
	public Object login4hiagt(String uname, String pwd) throws UserNotExistEx {
	Map m = getUserinfoByUid4hiagt(uname);
	if(m==null)
		throw new LoginException("ex:user_not_exist:此用户不存在");
	if(pwd.equals(m.get("pwd").toString()))
	{
		tksvr.setUtype("agent").setToken(uname, uname);
		tksvr.setTokenKeyVal("urole", "agent");
		if(m.get("parent_id")!=null)
			if(m.get("parent_id").equals("0"))
			tksvr.setTokenKeyVal("urole", "admin");
		return m;
	}
	throw new LoginException("ex:pwd_err:密码错误");
	
		
	}
	
	/**twigo dasi use
	 * 
	attilax    2016年11月14日  下午9:08:16
	 * @param sub_id
	 * @return
	 * @throws CantSetSelfEx
	 * @throws SuperiorExistEx
	 * @throws UserNotExistEx 
	 * @throws DuplicateEntryEx 
	 */
	public Object setSubAgent(String sub_id) throws UserNotExistEx,CantSetSelfEx, SuperiorExistEx,  DuplicateEntryEx
	{
		checkUserExist(sub_id);
		String getuid = tksvr.getuid();
		if(sub_id.equals(getuid))
			throw new CantSetSelfEx("ex:CantSetSelfEx:不能设置自己为代理");
		//checkSuperiorExist(sub_id);
		String sql="insert agent(uid,parent_id,pwd)values('$uid$','$pid$','$pwd$') ";
		sql=sql.replace("$uid$", sub_id);
		tksvr.setUtype("agent");
		sql=sql.replace("$pid$", getuid);
		sql=sql.replace("$pwd$", "111111");
	    try {
			return dbsvrV4.executeUpdateV2qb0(sql);
		}catch(DuplicateEntryEx e)
	    {
			throw new DuplicateEntryEx("已经存在此代理",e);
	    }
	    catch (getConnEx  | SQLException e) {
	    	ExUtil.throwExV2(e);
		}
		return sql;
		
	}

	/**
	attilax    2016年11月14日  下午9:15:56
	 * @param sub_id
	 * @throws UserNotExistEx 
	 */
	private void checkUserExist(String sub_id) throws UserNotExistEx {
		String sql = "select * from  account where id='$uid$' ";
		sql = sql.replace("$uid$", sub_id);
		tksvr.setUtype("agent");
	//	sql = sql.replace("$pid$", tksvr.getuid());
		sql = sql.replace("$pwd$", "111111");
		System.out.println(sql);
		List li = dbsvr.executeQuery(sql);
		if (li.size() == 0)
			throw new UserNotExistEx("用户不存在");

	}

	/**
	attilax    2016年11月14日  下午8:43:33
	 * @param sub_id
	 * @throws SuperiorExistEx 
	 */
	private void checkSuperiorExist(String sub_id) throws SuperiorExistEx {
	//	String sql
		String sql="select * from  account where id='$uid$' and promoter!=0";
		sql=sql.replace("$uid$", sub_id);
		tksvr.setUtype("agent");
		sql=sql.replace("$pid$", tksvr.getuid());
		sql=sql.replace("$pwd$", "111111");
	     List li = dbsvr.executeQuery(sql);
	      if(li.size()>0)
	    	  throw new SuperiorExistEx("已经存在绑定");
    // 	return	  li;
		
	}

	/**
	 * set twigwo dasi
	attilax    2016年11月14日  下午11:44:39
	 * @param sub_id
	 * @return
	 * @throws AuthEx
	 * @throws UserExistEx
	 * @throws OtherUserEx
	 */
	public Object setSubHiagt4adm(String sub_id) throws AuthEx, UserExistEx, OtherUserEx {
		tksvrV4.setUtype("admMod");
		try {
			tksvrV4.checkUidValid();
		} catch (UidEmptyEx e) {
			//throw new AuthEx("uid is empty", e);
		}
 
		String sql = "insert agent(uid,pwd)values('$uid$','$pwd$') ";
		sql = sql.replace("$uid$", sub_id);

		sql = sql.replace("$pid$", "");
		sql = sql.replace("$pwd$", "111111");
		try {
			return dbsvrV4.executeUpdateV2qb0(sql);
		}  catch ( DuplicateEntryEx   e) {
			throw new UserExistEx(e.getMessage(),e);
		}catch (  getConnEx | SQLException  e) {
			throw new OtherUserEx(e.getMessage(),e);
		}
		 

	}

	public Map getUserinfoByUid(String uid) {
		String sql="	select * from agent where uid='$uid$' ";
		sql=sql.replace("$uid$", uid);
		Map m=	dbsvr.uniqueResultAsRow(sql);
		return m;
	}
	
	public Map getUserinfoByUid4hiagt(String uid) throws UserNotExistEx {
		String sql="	select * from agent where uid='$uid$' and (parent_id is null or parent_id='') ";
		
		sql=sql.replace("$uid$", uid);
		System.out.println(sql);
		Map m=	dbsvr.uniqueResultAsRow(sql);
		if(m==null)
			throw new UserNotExistEx("用户不存在");
		return m;
	}

	@Inject 
	SqlService sqlSrv;
	@Deprecated
	public Object resetPwd() {
		HttpServletRequest req = Global.req.get();
		HttpSession sess = req.getSession();
		Set<String> capts = (Set<String>) sess.getAttribute("captSet");
		if (capts == null)
			throw new RuntimeException("chkex,capt_null,验证码错误capt_null");
		if (!capts.contains(req.getParameter("captcha")))
			throw new RuntimeException("chkex,capt_err,验证码错误");

		String sql = "update wxb_memeber set password='$pwd$' where account='$acc$'";
		String pwd = req.getParameter("password");
		sql = sql.replace("$pwd$", CTUtils.encryptBasedDes(pwd));
		sql = sql.replace("$acc$", req.getParameter("username"));
		if (req.getParameter("utype") != null)
			if (req.getParameter("utype").equals("mer")) {
				sql="";
				sql = "update wxb_customer set login_pwd='$pwd$' where login_name='$acc$'";
				pwd = req.getParameter("password");
				sql = sql.replace("$pwd$", CTUtils.encryptBasedDes(pwd));
				sql = sql.replace("$acc$", req.getParameter("username"));

			}
System.out.println("--resetPwd:"+sql);
		return sqlSrv.executeUpdate(sql);
		// StringUtil.getAttrFromPro("ct_user_password", null)));

	}
	
	@Inject
	TokenService tokenSrv;
	public Map getCurUserinfo()
	{
		tksvr.setUtype("Agent");
		String uid=tokenSrv.getuid(Global.req.get());	
		if("mer".equals(Global.req.get().getParameter("utype") ))
		{	tokenSrv.setModule("merMod");
			uid=tokenSrv.getuid(Global.req.get());	
			return MerUserInfo(uid);
		}
		
		
		Map m= getUserinfoByUid(uid);
	//orm.
		//String json=AtiJson.toJson(mi);
	return m;
		
//		Object mi;
//		if(mi==null)
//			throw new NotLoginEx("not_login_ex");
//		return new org.apache.commons.beanutils.BeanMap(mi);   
		
	}

	private Map MerUserInfo(String uid) {
		CustomerInfo mi=	JdbcTemplateTool.getCustomerInfo(uid);
		if(mi==null)
			throw new NotLoginEx("not_login_ex");
		return new org.apache.commons.beanutils.BeanMap(mi);   
	}


}
